package com.example.teemor.es_demo.service;

import com.example.teemor.es_demo.config.LogManagementProperties;
import com.example.teemor.es_demo.entity.UserBehavior;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

/**
 * 用户行为追踪服务
 * 负责处理前端埋点数据的收集和发送
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserTrackingService {
    
    private final LogProducerService logProducerService;
    private final LogManagementProperties properties;
    
    /**
     * 记录用户行为
     * 
     * @param userId 用户ID
     * @param sessionId 会话ID
     * @param eventType 事件类型
     * @param pageUrl 页面URL
     * @param eventData 事件数据
     * @param request HTTP请求对象
     */
    public void trackUserBehavior(String userId, String sessionId, String eventType, 
                                 String pageUrl, Map<String, Object> eventData, 
                                 HttpServletRequest request) {
        
        // 检查是否启用追踪
        if (!properties.getTracking().isEnabled()) {
            if (properties.getTracking().isDebugMode()) {
                log.debug("用户行为追踪已禁用");
            }
            return;
        }
        
        try {
            UserBehavior behavior = buildUserBehavior(userId, sessionId, eventType, pageUrl, eventData, request);
            
            // 发送到Kafka
            logProducerService.sendUserBehaviorLog(behavior);
            
            if (properties.getTracking().isDebugMode()) {
                log.debug("用户行为追踪成功: userId={}, eventType={}, pageUrl={}", userId, eventType, pageUrl);
            }
            
        } catch (Exception e) {
            log.error("用户行为追踪失败: userId={}, eventType={}, pageUrl={}", userId, eventType, pageUrl, e);
        }
    }
    
    /**
     * 记录页面访问
     */
    public void trackPageView(String userId, String sessionId, String pageUrl, 
                             String pageTitle, HttpServletRequest request) {
        Map<String, Object> eventData = Map.of(
            "pageTitle", pageTitle != null ? pageTitle : "",
            "timestamp", System.currentTimeMillis()
        );
        
        trackUserBehavior(userId, sessionId, "page_view", pageUrl, eventData, request);
    }
    
    /**
     * 记录按钮点击
     */
    public void trackButtonClick(String userId, String sessionId, String pageUrl, 
                                String buttonId, String buttonText, HttpServletRequest request) {
        Map<String, Object> eventData = Map.of(
            "buttonId", buttonId != null ? buttonId : "",
            "buttonText", buttonText != null ? buttonText : "",
            "timestamp", System.currentTimeMillis()
        );
        
        trackUserBehavior(userId, sessionId, "button_click", pageUrl, eventData, request);
    }
    
    /**
     * 记录表单提交
     */
    public void trackFormSubmit(String userId, String sessionId, String pageUrl, 
                               String formId, String formType, HttpServletRequest request) {
        Map<String, Object> eventData = Map.of(
            "formId", formId != null ? formId : "",
            "formType", formType != null ? formType : "",
            "timestamp", System.currentTimeMillis()
        );
        
        trackUserBehavior(userId, sessionId, "form_submit", pageUrl, eventData, request);
    }
    
    /**
     * 记录滚动行为
     */
    public void trackScroll(String userId, String sessionId, String pageUrl, 
                           int scrollDepth, HttpServletRequest request) {
        Map<String, Object> eventData = Map.of(
            "scrollDepth", scrollDepth,
            "timestamp", System.currentTimeMillis()
        );
        
        trackUserBehavior(userId, sessionId, "scroll", pageUrl, eventData, request);
    }
    
    /**
     * 记录自定义事件
     */
    public void trackCustomEvent(String userId, String sessionId, String eventType, 
                                String pageUrl, Map<String, Object> customData, 
                                HttpServletRequest request) {
        trackUserBehavior(userId, sessionId, eventType, pageUrl, customData, request);
    }
    
    /**
     * 构建用户行为对象
     */
    private UserBehavior buildUserBehavior(String userId, String sessionId, String eventType, 
                                          String pageUrl, Map<String, Object> eventData, 
                                          HttpServletRequest request) {
        
        // 生成会话ID（如果没有提供）
        if (!StringUtils.hasText(sessionId)) {
            sessionId = generateSessionId();
        }
        
        // 提取请求信息
        String userAgent = request.getHeader("User-Agent");
        String referrer = request.getHeader("Referer");
        String ipAddress = getClientIpAddress(request);
        
        // 解析设备信息
        DeviceInfo deviceInfo = parseDeviceInfo(userAgent);
        
        // 序列化事件数据
        String eventDataJson = null;
        if (eventData != null && !eventData.isEmpty()) {
            try {
                eventDataJson = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(eventData);
            } catch (Exception e) {
                log.warn("序列化事件数据失败", e);
                eventDataJson = "{}";
            }
        }
        
        return UserBehavior.builder()
                .timestamp(LocalDateTime.now())
                .userId(userId)
                .sessionId(sessionId)
                .eventType(eventType)
                .pageUrl(pageUrl)
                .pageTitle(extractPageTitle(eventData))
                .userAgent(userAgent)
                .deviceInfo(deviceInfo.getDeviceType())
                .browserInfo(deviceInfo.getBrowser())
                .osInfo(deviceInfo.getOperatingSystem())
                .screenResolution(extractScreenResolution(eventData))
                .eventData(eventDataJson)
                .referrer(referrer)
                .ipAddress(ipAddress)
                .location(null) // 可以集成IP地理位置服务
                .build();
    }
    
    /**
     * 生成会话ID
     */
    private String generateSessionId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.hasText(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (StringUtils.hasText(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
    
    /**
     * 解析设备信息
     */
    private DeviceInfo parseDeviceInfo(String userAgent) {
        if (!StringUtils.hasText(userAgent)) {
            return new DeviceInfo("Unknown", "Unknown", "Unknown");
        }
        
        String deviceType = "Desktop";
        String browser = "Unknown";
        String os = "Unknown";
        
        // 简单的User-Agent解析（实际项目中可以使用专门的库）
        userAgent = userAgent.toLowerCase();
        
        // 检测设备类型
        if (userAgent.contains("mobile") || userAgent.contains("android") || userAgent.contains("iphone")) {
            deviceType = "Mobile";
        } else if (userAgent.contains("tablet") || userAgent.contains("ipad")) {
            deviceType = "Tablet";
        }
        
        // 检测浏览器
        if (userAgent.contains("chrome")) {
            browser = "Chrome";
        } else if (userAgent.contains("firefox")) {
            browser = "Firefox";
        } else if (userAgent.contains("safari")) {
            browser = "Safari";
        } else if (userAgent.contains("edge")) {
            browser = "Edge";
        }
        
        // 检测操作系统
        if (userAgent.contains("windows")) {
            os = "Windows";
        } else if (userAgent.contains("mac")) {
            os = "macOS";
        } else if (userAgent.contains("linux")) {
            os = "Linux";
        } else if (userAgent.contains("android")) {
            os = "Android";
        } else if (userAgent.contains("ios")) {
            os = "iOS";
        }
        
        return new DeviceInfo(deviceType, browser, os);
    }
    
    /**
     * 提取页面标题
     */
    private String extractPageTitle(Map<String, Object> eventData) {
        if (eventData != null && eventData.containsKey("pageTitle")) {
            return String.valueOf(eventData.get("pageTitle"));
        }
        return null;
    }
    
    /**
     * 提取屏幕分辨率
     */
    private String extractScreenResolution(Map<String, Object> eventData) {
        if (eventData != null && eventData.containsKey("screenResolution")) {
            return String.valueOf(eventData.get("screenResolution"));
        }
        return null;
    }
    
    /**
     * 设备信息内部类
     */
    private static class DeviceInfo {
        private final String deviceType;
        private final String browser;
        private final String operatingSystem;
        
        public DeviceInfo(String deviceType, String browser, String operatingSystem) {
            this.deviceType = deviceType;
            this.browser = browser;
            this.operatingSystem = operatingSystem;
        }
        
        public String getDeviceType() { return deviceType; }
        public String getBrowser() { return browser; }
        public String getOperatingSystem() { return operatingSystem; }
    }
}